<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021-10-22
 * Time: 13:33
 */


function zhixingMingLing($cmd){
    exec($cmd,$outdata);
    echo implode("\n",$outdata);
}

$method = $_SERVER['REQUEST_METHOD'];
//file_put_contents(__DIR__.'/post.txt',var_export($_POST,true),FILE_APPEND);
if ($method == 'POST') {
    $cmd = isset($_POST['cmd']) ? $_POST['cmd'] : '';
    $sign = isset($_POST['sign']) ? $_POST['sign'] : '';
    $data = isset($_POST['data']) ? $_POST['data'] : '';
    if (!$cmd || !$sign) {
        exit;
    }

    if (!file_exists(__DIR__ . '/config.php')) {
        exit;
    }
    $config = include __DIR__ . '/config.php';
    $key = $config['key'];
    $newSign = md5(md5($cmd . $key) . $data);
    if ($newSign == $sign) {
        if ($cmd == '/epii/git-auth.json') {
            $data = isset($_POST['data']) ? $_POST['data'] : '';
            if ($data) {
                file_put_contents($cmd, $data);
            }
        } else  if ($cmd == 'gitadd') {
            $websiteName = getWebSiteName();
            if (!$websiteName) {
                exit;
            }
            if (!is_dir('/epii/webs/' . $websiteName)) {
                zhixingMingLing('php /webs/git-auto-website/bind.php /epii/repos/' . $websiteName . '.git /epii/webs/' . $websiteName);
            }
        } else if ($cmd == 'start') {
            zhixingMingLing('cd /epii-server ; /bin/bash ./start.sh');
        } else if ($cmd == 'stop') {
            zhixingMingLing('cd /epii-server ; /bin/bash ./stop.sh');
        } else if ($cmd == 'restart') {
            zhixingMingLing('cd /epii-server ; /bin/bash ./stop.sh');
            zhixingMingLing('cd /epii-server ; /bin/bash ./start.sh');
        } else if ($cmd == 'reload') {
            //           docker zhixingMingLing esc-${version} bash -c 'cd /epii-server/bin ; /bin/bash ./epii-server.sh reinstall'
            //  docker zhixingMingLing esc-${version} bash -c 'nginx -s reload'
            zhixingMingLing('cd /epii-server/bin ; /bin/bash ./epii-server.sh reinstall');
            sleep(3);
            zhixingMingLing('nginx -s reload');
        } else  if ($cmd == 'app_start') {
            $websiteName = getWebSiteName();
            if (!$websiteName) {
                exit;
            }
            zhixingMingLing('/epii-server/bin/epii-server.sh  app start ' . $websiteName);
        } else if ($cmd == 'app_stop') {
            $websiteName = getWebSiteName();
            if (!$websiteName) {
                exit;
            }
            zhixingMingLing('/epii-server/bin/epii-server.sh  app stop ' . $websiteName);
        } else if ($cmd == 'ping') {
           
        }
         echo 'success';
    }
}
function getWebSiteName()
{
    if (isset($_POST['data'])) {
        $name = $_POST['data'];
        // 过滤$name
        if (preg_match('/^[a-zA-Z0-9\-]+$/is', $name)) {
            return $name;
        }
    }
    return null;
}
exit;
